<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <Authority :value="'dept.add'">
          <a-button type="primary" @click="handleCreate"> 新增部门 </a-button>
        </Authority>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="[
            {
              icon: 'clarity:note-edit-line',
              auth: 'dept.edit',
              onClick: handleEdit.bind(null, record)
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              auth: 'dept.del',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: handleDelete.bind(null, record)
              }
            }
          ]" />
        </template>
      </template>
    </BasicTable>
    <DeptModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { removeOrg, getOrgTree } from '/@/api/system/dept';
import { useModal } from '/@/components/Modal';
import { Authority } from '/@/components/Authority';
import DeptModal from './DeptModal.vue';
import { columns, searchFormSchema } from './dept.data';
import { onMounted } from 'vue';

onMounted(() => {
  setTimeout(() => {
    expandAll();
  }, 200);
});

const [registerModal, { openModal }] = useModal();
const [registerTable, { reload, expandAll }] = useTable({
  title: '部门列表',
  isTreeTable: true,
  api: getOrgTree,
  columns,
  formConfig: {
    labelWidth: 90,
    schemas: searchFormSchema
  },
  pagination: false,
  striped: false,
  useSearchForm: true,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  canResize: false,
  defaultExpandAllRows: true,
  actionColumn: {
    width: 80,
    title: '操作',
    dataIndex: 'action'
  }
});

function handleCreate() {
  openModal(true, {
    isUpdate: false
  });
}

function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true
  });
}

async function handleDelete(record: Recordable) {
  await removeOrg([record['id']]);
  reload();
}

function handleSuccess() {
  reload();
}
</script>
